<template>
  <div id="main">
    <div v-if="flag">
      <div style="margin-top: 1%; margin-bottom: 1%; text-align: right;">
        <el-button @click="deleteFiles" v-if="userType === '管理员'">删除</el-button>
        <el-button @click="downloadFile" >下载</el-button>
        <el-button @click="historyRecord" v-if="userType === '管理员'">历史</el-button>
      </div>
      <dm-table ref="fileTable" :table-data="tableData" @rename="rename" @handleSelectionChange="handleSelectionChange"
                @enterFolder="enterFolder" @deleteFile="deleteFile"></dm-table>
      <rename-dialog :form="form" @sure="renameSubmit" :dialog-attribute="renameAttr"></rename-dialog>
    </div>
    <div v-else>
      <el-button @click="historyRecord" style="margin-bottom: 1%">返回</el-button>
      <history-record></history-record>
    </div>
  </div>

</template>

<script>
  import DmTable from './file/table'
  import {fileService} from '../../service/fileService'
  import RenameDialog from './file/dialog/renameDialog'
  import {Msg} from '../../tools/message'
  import {recordService} from '../../service/recordService'
  import HistoryRecord from './record/index'
  import {folderService} from '../../service/folderService'

  export default {
    name: 'dmMain',
    components: {HistoryRecord, RenameDialog, DmTable},
    data () {
      return {
        tableData: [],
        type: {
          'xls': '#icon-xls',
          'doc': '#icon-doc',
          'docx': '#icon-doc',
          'ppt': '#icon-ppt',
          'png': '#icon-png',
          'txt': '#icon-txt',
          'pdf': '#icon-pdf',
          'jpg': '#icon-jpg',
          'gif': '#icon-gif'
        },
        folder: {}, // 要修改的文件夹
        file: {}, // 重命名文件的信息
        form: {}, // 重命名弹框的属性值
        downloadFiles: [], // 要下载的文件信息
        fileIds: [],
        fileRelativePaths: [],
        flag: true,
        currentFolderId: this.folderId, // 当前文件夹ID
        renameAttr: {
          title: '文件重命名',
          label: '文件名',
          isFolder: false
        },
        userType: this.$store.getters.userInfo.userType
      }
    },
    props: {
      folderId: {
        type: Number,
        default: 0
      },
      folderPath: {
        type: String,
        default: ''
      },
      filesData: {
        type: Array,
        default () {
          return []
        }
      }
    },
    computed: {
      getFolderTree () {
        return this.$store.state.folder.isAddFolder
      }
    },
    watch: {
      folderId: function (val) {
        this.currentFolderId = val
        this.findFilesByFolder()
      },
      filesData: function (val) {
        this.tableData = val
        this.getFileType()
      },
      getFolderTree (val) {
        console.log(val, 'ddd')
        this.findFilesByFolder()
        this.$store.state.folder.isAddFolder = false
      }
    },
    created () {
      this.findFilesByFolder()
    },
    methods: {
      enterFolder (row) { // 从表格中进入文件夹
        this.currentFolderId = row.folderId
        // 为避免vue.js对数组的监听而改变上一级文件的操作，进行循环遍历重新生成
        let paths = this.$store.state.folder.currentPath.paths
        let path = ''
        paths.forEach(e => {
          path += e + '/'
        })
        path += row.folderName
        this.$store.commit('SET_PATHS', {nextPath: path.split('/'), nextFolderId: row.folderId})
        this.findFilesByFolder()
      },
      findFilesByFolder () { // 通过文件夹去查询文件和文件夹
        fileService.findFilesByFolder({
          userId: this.$store.getters.userInfo.userId,
          folderId: this.currentFolderId
        }).then(res => {
          this.tableData = res.data.data
          this.getFileType()
        }).catch(error => {
          console.log(error)
        })
      },
      getFileType () { // 获取文件类型
        let tableDataTemp = []
        this.tableData.forEach(e => {
          e.isFolder = true
          if (!e.folderId) {
            let suffix = e.fileName.substring(e.fileName.lastIndexOf('.') + 1)
            e.fileType = this.type[suffix]
            e.suffix = suffix
            e.isFolder = false
          }
          tableDataTemp.push(e)
        })
        this.tableData = tableDataTemp
      },
      rename (row) {
        this.$store.commit('setRenameDialogVisible')
        if (row.isFolder) {
          this.form.name = row.folderName
          this.folder = row
          this.folder.oldFolderName = row.folderName

          this.renameAttr.title = '文件夹重命名'
          this.renameAttr.label = '文件夹名'
          this.renameAttr.isFolder = true
        } else {
          this.form.name = row.fileName

          this.file = row
          this.file.oldFileName = row.fileName
          this.renameAttr.title = '文件重命名'
          this.renameAttr.label = '文件名'
          this.renameAttr.isFolder = false
        }
      },
      renameSubmit () {
        if (this.renameAttr.isFolder) {
          this.folderRenameSubmit()
        } else {
          this.fileRenameSubmit()
        }
        this.$store.commit('setRenameDialogVisible') // 关闭弹框
      },
      fileRenameSubmit () { // 文件重命名提交
        this.file.fileName = this.form.name
        if (this.file.fileName === this.file.oldFileName) {
          Msg.warn('新文件名和旧文件名相同')
        } else {
          this.file.userId = this.$store.getters.userInfo.userId
          fileService.fileRename(this.file).then(res => {
            if (res.data.status) {
              Msg.success(res.data.msg)
            } else {
              Msg.warn(res.data.msg)
            }
          }).catch(error => {
            console.log(error)
          })
        }
      },
      folderRenameSubmit () { // 文件夹重命名提交
        this.folder.folderName = this.form.name
        folderService.folderRename(this.folder).then(res => {
          if (res.data.status) {
            Msg.success(res.data.msg)
          } else {
            Msg.warn(res.data.msg)
          }
        }).catch(error => {
          console.log(error)
        })
      },
      handleSelectionChange (val) {
        this.downloadFiles = val
        this.fileIds = []
        this.fileRelativePaths = []
        val.forEach(e => {
          this.fileIds.push(e.fileId)
          this.fileRelativePaths.push(e.relativePath)
        })
      },
      deleteFiles () {
        if (this.fileIds.length > 0) {
          this.$confirm('是否永久删除文件，是否继续', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            fileService.deleteFiles({
              userId: this.$store.getters.userInfo.userId,
              ids: this.fileIds.toString(),
              fileRelativePaths: this.fileRelativePaths.toString()
            }).then(res => {
              if (res.data.status) {
                Msg.success(res.data.msg)
                this.findFilesByFolder()
              } else {
                Msg.error(res.data.msg)
              }
              this.$refs.fileTable.clearSelection()
            }).catch(error => {
              console.log(error)
              this.$refs.fileTable.clearSelection()
            })
          }).catch(() => {
            Msg.info('已取消删除')
            this.$refs.fileTable.clearSelection()
          })
        } else {
          Msg.warn('未选择任何文件')
        }
      },
      deleteFile (row) {
        this.fileIds = []
        this.fileRelativePaths = []
        this.fileIds.push(row.fileId)
        this.fileRelativePaths.push(row.relativePath)
        this.deleteFiles()
      },
      downloadFile () {
        if (this.fileIds.length > 0) {
          let href = ''
          if (this.fileIds.length === 1) {
            href = 'http://localhost:8090/dm/file/downloadFile?ids=' + this.downloadFiles[0].relativePath + '&attachname=' + this.downloadFiles[0].fileName

          } else {
            href = 'http://localhost:8090/dm/file/downloadMultiFile?ids=' + this.fileIds.toString()
          }
          this.createClickEvent(href)
          this.$refs.fileTable.clearSelection()
        } else {
          Msg.warn('未选择任何文件')
        }
      },
      createClickEvent (href) {
        // 创建a标签
        let a = document.createElement('a')
        let e = document.createEvent('MouseEvents')
        // 创建鼠标事件对象初始化事件对象
        e.initEvent('click', false, false)
        // 设置下载地址
        a.href = href
        // 给指定的元素，执行事件click事件
        a.dispatchEvent(e)
      },
      historyRecord () {
        this.flag = !this.flag
      }
    }
  }
</script>

<style lang="scss" scoped>
  #main {
    .el-input__inner {
      height: 30px;
    }
  }
</style>
